/*******************************************************************************
 * Copyright (c) 2009 Kevin Bierhoff and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *     Kevin Bierhoff - initial API and implementation
 *******************************************************************************/
package com.googlecode.twelfdevtools.server;

import java.io.IOException;

import org.eclipse.core.resources.IProject;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;

import com.googlecode.twelfdevtools.TwelfActivator;
import com.googlecode.twelfdevtools.preferences.PreferenceConstants;
import com.googlecode.twelfdevtools.preferences.TwelfPreferencesAccess;


public class TwelfServer {
	
	public static final String WINDOWS_DEFAULT_PATH = "C:\\Program Files\\Twelf\\bin\\twelf-server.bat";

	public static final String MACOSX_DEFAULT_PATH = "/Applications/Twelf/bin/twelf-server";

	private final TwelfProcess twelfProcess;
	private final TwelfOutputProcessor twelfOutput;
	private final IProject project;

	public TwelfServer(IProject project) throws IOException {
		this.project = project;
		TwelfActivator.getDefault().getPreferenceStore().
				addPropertyChangeListener(new TwelfCommandPreferenceListener());
		twelfProcess = new TwelfProcess(project, TwelfPreferencesAccess.getTwelfCommand());
		twelfOutput = new TwelfOutputProcessor(twelfProcess.getStdOut());
		new Thread(twelfOutput).start();
	}

	public void addTwelfServerListener(TwelfServerListener l) {
		twelfOutput.addTwelfServerListener(l);
	}

	public void removeTwelfServerListener(TwelfServerListener l) {
		twelfOutput.removeTwelfServerListener(l);
	}

	public synchronized void kill() {
		twelfProcess.kill();
	}

	public synchronized void loadFile(String fileName) {
		twelfProcess.loadFile(fileName);
	}

	public synchronized void make() {
		twelfProcess.make();
	}

	public synchronized void quit() {
		twelfProcess.quit();
	}
	
	private synchronized void restart(String cmd) {
		twelfProcess.restart(project, cmd);
	}
	
	private class TwelfCommandPreferenceListener implements IPropertyChangeListener {

		public void propertyChange(PropertyChangeEvent event) {
			if(PreferenceConstants.P_SERVER_CMD.equals(event.getProperty()) &&
					event.getNewValue() != null) {
				TwelfServer.this.restart((String) event.getNewValue());
			}
			
		}

	}

}
